<template>
  <div class="health-container">
    <!-- 导航栏 -->
    <header class="admin-header">

    </header>


    <!-- 主要内容 -->
    <main class="main-content">
      <div class="container">
        <h2>评价管理</h2>

        <div class="filter-section">
          <el-input
              v-model="searchQuery"
              placeholder="输入评价ID/用户ID/陪诊员ID"
              clearable
              style="width: 300px"
              @clear="handleSearchClear"
              @keyup.enter="selectReviews"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-select
              v-model="searchType"
              placeholder="搜索类型"
              style="width: 120px; margin-left: 10px"
          >
            <el-option label="评价ID" value="id" />
            <el-option label="用户ID" value="userId" />
            <el-option label="陪诊员ID" value="escortId" />
          </el-select>

          <el-button
              type="primary"
              @click="selectReviews"
              style="margin-left: 10px"
          >
            搜索
          </el-button>
        </div>


        <!-- 评价卡片列表 -->
        <div class="review-cards">
          <div v-for="review in paginatedReviews" :key="review.id" class="review-card">
            <div class="card-header">
              <div class="user-info">
                <div class="name-rating">
                  <h3>{{ review.userName }}</h3>
                  <div class="rating-stars">
                    <el-rate
                        v-model="review.rating"
                        disabled
                        show-score
                        text-color="#ff9900"
                        score-template="{value} 星"
                    />
                  </div>
                </div>
              </div>
              <div class="review-id">评价ID: {{ review.id }}</div>
            </div>

            <div class="card-body">
              <div class="info-row">
                <div class="info-item">
                  <span class="label">陪诊员ID:</span>
                  <span class="value">{{ review.escortId }}</span>
                </div>
                <div class="info-item">
                  <span class="label">预约ID:</span>
                  <span class="value">{{ review.appointmentId }}</span>
                </div>
              </div>

              <div class="review-content">
                <span class="label">评价内容:</span>
                <p class="content-text">{{ review.content || '用户未填写评价内容' }}</p>
              </div>

              <div class="review-time">
                <span class="label">评价时间:</span>
                <span class="value">{{ formatDateTime(review.createTime) }}</span>
              </div>
            </div>

            <div class="card-footer">
              <el-button
                  type="danger"
                  @click="confirmDeleteReview(review.id)"
                  :loading="loadingMap[`delete-${review.id}`]"
                  size="small"
              >
                <el-icon><Delete /></el-icon>
                删除评价
              </el-button>
            </div>
          </div>

          <div v-if="reviewList.length === 0" class="empty-state">
            <el-empty description="暂无评价数据" />
          </div>

          <!-- 分页控件 -->
          <div class="pagination" v-if="reviewList.length > 0">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :total="totalReviews"
                layout="total, prev, pager, next, jumper"
                @current-change="handlePageChange"
                background
            />
          </div>

        </div>
      </div>
    </main>

    <!-- 页脚 -->
    <footer style="background-color: #f5f7fa; padding: 20px 0; border-top: 1px solid #e6e6e6;">
      <div class="container">
        <div class="footer-content" style="text-align: center;">
          <p style="color: #666; margin-bottom: 10px;">安心陪诊后台管理系统</p>
          <p style="color: #999; font-size: 12px;">
            &copy; 2025 安心陪诊平台 版权所有 |
            <a href="#" @click.prevent="goToUserAgreement" style="color: #999;">用户协议</a> |
            <a href="#" @click.prevent="goToPrivacyPolicy" style="color: #999;">隐私政策</a>
          </p>
        </div>
      </div>
    </footer>
  </div>
</template>

<script setup>
import {ref, onMounted, computed} from "vue";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import {useRouter} from "vue-router";
import {Search, Delete} from '@element-plus/icons-vue';

const router = useRouter();

const searchType = ref('评价ID'); // 默认按评价ID搜索

const handleSearchClear = () => {
  searchQuery.value = '';
  searchType.value = 'id';
  fetchReviews(); // 调用原始的获取全部评价方法
};

const reviewList = ref([
  {
    id: '',
    userId: '',
    userName: '',
    escortId: '',
    appointmentId: '',
    rating: '',
    content: '',
    createTime: ''
  }
]);
const loadingMap = ref({});

// 搜索和筛选相关
const searchQuery = ref('');
const ratingFilter = ref(null);
const dateRange = ref([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(6);
const totalReviews = ref(0);

// 分页计算属性
const paginatedReviews = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return reviewList.value.slice(start, end);
});

// 获取评价列表
const fetchReviews = async () => {
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    };

    if (searchQuery.value) {
      params.search = searchQuery.value;
    }

    if (ratingFilter.value) {
      params.rating = ratingFilter.value;
    }

    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = formatDateForAPI(dateRange.value[0]);
      params.endDate = formatDateForAPI(dateRange.value[1]);
    }

    const response = await axios.get(BASE_URL + '/v1/manager/reviews', {
      params,
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('managerToken')}`
      }
    });

    if (response.data.state === 2000) {
      reviewList.value = response.data.data;
      totalReviews.value = response.data.data.total || 0;
    } else {
      ElMessage.error(response.data.message || "获取评价列表失败");
    }
  } catch (error) {
    console.error("获取评价列表出错:", error);
    ElMessage.error(error.response?.data?.message || "获取评价列表失败");
  }
};

//搜索相关评价
const selectReviews = async () => {
  try {
    const requestData = {
      id: null,
      userId: null,
      escortId: null
    };
    // 根据搜索类型设置对应字段
    if (searchQuery.value) {
      switch (searchType.value) {
        case 'id':
          requestData.id = Number(searchQuery.value);
          break;
        case 'userId':
          requestData.userId = Number(searchQuery.value);
          break;
        case 'escortId':
          requestData.escortId = Number(searchQuery.value);
          break;
      }
    }

    const response = await axios.post(
        BASE_URL + '/v1/manager/reviewSelect',
        requestData,
        {
          headers: {
            'Content-Type': 'application/json' // 明确指定Content-Type
          }
        }
    );
    console.log(requestData);

    if (response.data.state === 2000) {
      reviewList.value = response.data.data;
      totalReviews.value = response.data.data.length || 0;
      currentPage.value = 1; // 搜索后重置到第一页
    } else {
      ElMessage.error(response.data.message || "搜索评价失败");
    }
  } catch (error) {
    console.error("搜索评价出错:", error);
    ElMessage.error(error.response?.data?.message || "搜索评价失败");
  }
};

// 删除评价
const deleteReview = async (reviewId) => {
  const loadingKey = `delete-${reviewId}`;
  loadingMap.value[loadingKey] = true;

  try {
    const response = await axios.post(
        `${BASE_URL}/v1/manager/delReviews`,
        null,
        {
          params: {reviewId},
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('managerToken')}`
          }
        }
    );

    if (response.data.state === 2000) {
      ElMessage.success("删除评价成功");
      await fetchReviews();
    } else {
      ElMessage.error(response.data.message || "删除评价失败");
    }
  } catch (error) {
    console.error("删除评价出错:", error);
    ElMessage.error(error.response?.data?.message || "删除评价失败");
  } finally {
    loadingMap.value[loadingKey] = false;
  }
};

// 确认删除对话框
const confirmDeleteReview = (reviewId) => {
  ElMessageBox.confirm(
      '确定要删除这条评价吗？删除后不可恢复。',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    deleteReview(reviewId);
  }).catch(() => {
    // 用户取消操作
  });
};

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return "未知时间";
  const date = new Date(dateString);
  return date.toLocaleString();
};

// 格式化日期为API需要的格式 (YYYY-MM-DD)
const formatDateForAPI = (date) => {
  return date.toISOString().split('T')[0];
};


const goToUserAgreement = () => {
  router.push("/userAgreement");
};

const goToPrivacyPolicy = () => {
  router.push("/privacyPolicy");
};


onMounted(() => {
  fetchReviews();
});
</script>

<style scoped>
.health-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f8fafc;
}

.admin-header {
  color: white;
  padding: 15px 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.main-content {
  flex: 1;
  padding: 30px 0;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 25px;
}

h2 {
  font-size: 24px;
  color: #1a365d;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e2e8f0;
  font-weight: 600;
}

/* 搜索和筛选区域 */
.filter-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  margin-bottom: 25px;
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
  align-items: center;
}

.filter-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.filter-section .el-input {
  margin-right: 10px;
}

.search-button {
  margin-left: 10px;
}

/* 评价卡片容器 */
.review-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 25px;
  margin-top: 20px;
}

/* 评价卡片样式 */
.review-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
  overflow: hidden;
  transition: all 0.3s ease;
  border: 1px solid #e2e8f0;
  display: flex;
  flex-direction: column;
}

.review-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
  border-color: #cbd5e0;
}

.card-header {
  padding: 18px 20px;
  background-color: #f7fafc;
  border-bottom: 1px solid #edf2f7;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #4299e1;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.name-rating {
  display: flex;
  flex-direction: column;
}

.name-rating h3 {
  margin: 0;
  font-size: 16px;
  color: #2d3748;
  font-weight: 500;
}

.rating-stars {
  margin-top: 6px;
}

.review-id {
  font-size: 12px;
  color: #718096;
  background: #edf2f7;
  padding: 3px 8px;
  border-radius: 10px;
}

.card-body {
  padding: 20px;
  flex: 1;
}

.info-row {
  display: flex;
  margin-bottom: 16px;
  gap: 15px;
}

.info-item {
  flex: 1;
  min-width: 0;
}

.label {
  font-weight: 500;
  color: #4a5568;
  margin-right: 5px;
  font-size: 14px;
}

.value {
  color: #2d3748;
  font-size: 14px;
  word-break: break-all;
}

.review-content {
  margin: 18px 0;
}

.content-text {
  margin-top: 8px;
  color: #4a5568;
  line-height: 1.6;
  font-size: 14px;
  background: #f8fafc;
  padding: 12px;
  border-radius: 6px;
  border-left: 3px solid #4299e1;
}

.review-time {
  font-size: 13px;
  color: #718096;
  display: flex;
  align-items: center;
  gap: 5px;
}

.review-time .label {
  font-size: 13px;
}

.card-footer {
  padding: 15px 20px;
  border-top: 1px solid #edf2f7;
  display: flex;
  justify-content: flex-end;
  background-color: #f7fafc;
}

/* 空状态样式 */
.empty-state {
  grid-column: 1 / -1;
  padding: 60px 0;
  text-align: center;
}

/* 分页样式 */
.pagination {
  grid-column: 1 / -1;
  display: flex;
  justify-content: center;
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #e2e8f0;
}

/* 按钮样式 */
.el-button {
  border-radius: 6px;
  font-weight: 500;
}

.el-button--danger {
  background-color: #f56565;
  border-color: #f56565;
}

.el-button--danger:hover {
  background-color: #e53e3e;
  border-color: #e53e3e;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .review-cards {
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 15px;
  }

  .review-cards {
    grid-template-columns: 1fr;
  }

  .filter-section {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }

  .info-row {
    flex-direction: column;
    gap: 10px;
  }
}

@media (max-width: 480px) {
  h2 {
    font-size: 20px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .review-id {
    align-self: flex-start;
  }
}
</style>